package com.lb.base.util;

import javax.servlet.http.HttpServletRequest;

/**
 * 功能
 *
 * @author libin
 */
public class IpUtils {

    private static final String X_FORWARDED_FOR_HEADER = "x-forwarded-for";

    private static final String REAL_IP_HEADER = "X-Real-IP";

    private static final String X_TRUE_IP = "x-true-ip";

    /**
     * 获取远程ip
     *
     * @param request
     */
    public static String getRemoteAddr(HttpServletRequest request) {
        String ip = request.getHeader(X_TRUE_IP);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = request.getHeader(X_FORWARDED_FOR_HEADER);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if (index != -1) {
                return ip.substring(0, index);
            } else {
                return ip;
            }
        }
        ip = request.getHeader(REAL_IP_HEADER);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)) {
            return ip;
        }
        return request.getRemoteAddr();
    }

    public static void main(String[] args) {
        LockUtils.falseValueOfType(void.class);
//        System.out.println(RuntimeUtil.execForStr("ipconfig"));
    }

}